#!/bin/bash

# =============================================================================
# macOS 快速构建脚本 (简化版)
# LimeReader Quick Build Script
# =============================================================================

set -e

echo "🚀 开始快速构建 macOS Release 版本..."

# 基本配置
QT_PATH="/opt/homebrew/opt/qt6"
BUILD_DIR="build"

# 1. 清理并创建构建目录
echo "📁 清理构建目录..."
rm -rf $BUILD_DIR
mkdir $BUILD_DIR && cd $BUILD_DIR

# 2. CMake 配置
echo "⚙️  配置 CMake..."
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH=$QT_PATH ..

# 3. 构建项目
echo "🔨 执行构建..."
cmake --build . --config Release --parallel

# 4. 部署Qt依赖
echo "📦 部署依赖..."
cmake --build . --target deploy_mac

# 5. 添加关键依赖
echo "🔧 添加关键依赖..."
cp -r "$QT_PATH/lib/QtDBus.framework" "bin/LimeReader.app/Contents/Frameworks/"
cp "/opt/homebrew/lib/libpoppler.153.dylib" "bin/LimeReader.app/Contents/Frameworks/"

# 6. 修复依赖路径
echo "🔗 修复依赖路径..."
install_name_tool -change "@rpath/libpoppler.153.dylib" \
    "@executable_path/../Frameworks/libpoppler.153.dylib" \
    "bin/LimeReader.app/Contents/Frameworks/libpoppler-cpp.2.dylib"

# 7. 清理签名冲突
echo "🧹 清理签名文件..."
rm -rf bin/LimeReader.app/Contents/_CodeSignature 2>/dev/null || true
rm -rf bin/LimeReader.app/Contents/MacOS/icons/ 2>/dev/null || true

# 8. 代码签名
echo "✍️  执行代码签名..."
find bin/LimeReader.app/Contents/Frameworks -name "*.framework" -exec codesign -f -s - {} \; 2>/dev/null || true
find bin/LimeReader.app/Contents/Frameworks -name "*.dylib" -exec codesign -f -s - {} \; 2>/dev/null || true
find bin/LimeReader.app/Contents/PlugIns -name "*.dylib" -exec codesign -f -s - {} \; 2>/dev/null || true
codesign -f -s - bin/LimeReader.app/Contents/MacOS/LimeReader
codesign -f -s - bin/LimeReader.app

echo "✅ 构建完成！"
echo "📍 应用位置: $(pwd)/bin/LimeReader.app"
echo "🚀 启动应用: open bin/LimeReader.app"